package org.kpli.jak.net.second;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 
 * @author dnd
 * 
 */
public class MultiThreadChatClient implements Runnable {

	static Socket clientSocket = null;
	static PrintStream printStream = null;
	static DataInputStream dataInput = null;
	static BufferedReader inputLine = null;
	static boolean closed = false;

	public static void main(String[] args) {

		// port default
		int port_number = 2211;
		String host = "localhost";

		if (args.length < 2) {
			System.out.println("Usage: java MultiThreadChatClient  \n"
					+ "Host yang digunakan=" + host + ", Nomer Port="
					+ port_number);
		} else {
			host = args[0];
			port_number = Integer.valueOf(args[1]).intValue();
		}
		/**
		 * Membuka socket dengan memberikan host dan port dan membuka input dan
		 * output
		 */
		try {
			clientSocket = new Socket(host, port_number);
			inputLine = new BufferedReader(new InputStreamReader(System.in));
			printStream = new PrintStream(clientSocket.getOutputStream());
			dataInput = new DataInputStream(clientSocket.getInputStream());
		} catch (UnknownHostException e) {
			System.err.println("HOST TAK TERDETEKSI " + host);
		} catch (IOException e) {
			System.err
					.println("Couldn't get I/O for the connection to the host "
							+ host);
		}

		if (!clientSocket.equals(null) && !printStream.equals(null)
				&& !dataInput.equals(null)) {
			try {

				// membuat thread untuk membaca dari server
				new Thread(new MultiThreadChatClient()).start();

				while (!closed) {
					printStream.println(inputLine.readLine());
				}

				printStream.close();
				dataInput.close();
				clientSocket.close();
			} catch (IOException e) {
				System.err.println("IOException:  " + e);
			}
		}
	}

	@SuppressWarnings("deprecation")
	public void run() {
		String responseLine;

		// server tetap akan hidup selama kita belum menulis "bye""
		try {
			while ((responseLine = dataInput.readLine()) != null) {
				System.out.println(responseLine);
				if (responseLine.indexOf("*** Bye") != -1)
					break;
			}
			closed = true;
		} catch (IOException e) {
			System.err.println("IOException:  " + e);
		}
	}

}
